<template>
	<view>
		<!-- 顶部 logo 搜索框 -->
		<view style="display: flex;">
			<view class="logo2">
				<image src="/static/images/left.png" class="left-icon" @click="backToLast"></image>
			</view>
			<view class="search" style="display: flex;"> 
				<!-- @clear="searchAll" @custom="searchAction" :actionStyle="{width:'100rpx'}"
				:actionText="$t('search')"-->
				<up-search :placeholder="$t('search')" v-model="keyword" :show-action="false"
					:clearabled="true" bgColor="rgba(187,187,187,0.1)" borderColor="rgba(187,187,187,0.1)"
					placeholder-color="#FFFFFF" search-icon-color="#FFFFFF" height="1.7rem" @search="searchAction"
					focus style="background-color: rgba(187,187,187,0.6);border-radius: 64rpx;"></up-search>
				<view style="margin: 0.3rem 0 0 0.5rem;font-size: 15px;" @click="searchAction(keyword)">
					{{$t('search')}}
				</view>
				<!-- <image src="/static/icon/camera.png" class="icon-camera" alt="icon"></image>  ,marginLeft:'-10rpx'-->
			</view>
		</view>
		<MessagePrompt v-model:isShow="isShow" v-model:title="title"></MessagePrompt>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted, watch } from "vue";
	import { useCommonStore } from "../stores/useCommonStore";
	import { getProductStyle, searchProduct, searchFunplay } from '../api/productList.js'
	import { ProductListType, StyleImg, SearchPost,SearchProduct } from '../types/types'
	import MessagePrompt from '@/components/messagePrompt.vue'
	import { string } from "../uni_modules/uview-plus/libs/function/test";
	import { onShow } from "@dcloudio/uni-app";
	import { useI18n } from 'vue-i18n'
	const { t } = useI18n()
	onShow(() => {

	})
	// 组件挂载时自动调用getMenuList获取数据
	onMounted(() => {

	});
	// 定义接收的props
	const props = defineProps({
		modelValue: {
			type: String,
			required: true
		},
		searchCate: {   //搜索类别 ：盲盒0 还是 广场1
			type: Number,
			required: true
		}
	});
	const emits = defineEmits(['update:modelValue', 'update:searchCate', 'search']);
	// 使用一个本地变量来追踪输入值
	const keyword = ref(props.modelValue)
	// 搜索类别0, 1  决定调用哪个接口
	const searchCate = ref(0)
	// 从哪一页来的 list or square
	const pageSource = ref('')
	const isShow = ref<boolean>(false);
	const title = ref<String>("")
	const commonStore = useCommonStore();
	// 动态参数 获取产品的参数
	const params = ref({
		current: 1,
		// lang: uni.getStorageSync('lang'),
		product_name: ''
	});
	// 动态参数 获取帖子的参数
	const params3 = ref({
		current: 1,
		// lang: uni.getStorageSync('lang'),
		funpalytitle: ''
	});
	// 动态参数  获取款式的参数
	const params2 = ref({
		lang: uni.getStorageSync('lang'),
		productId: ''
	});

	const backToLast = () => {
		// uni.navigateBack()  navigateTo  switchTab
		pageSource.value = commonStore.pageSource
		if (commonStore.pageSource == 'list') {
			uni.switchTab({
				url: '/pages/list/list'
			})
		} else if (commonStore.pageSource == 'square') {
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	}

	// 监听props变化，更新本地值
	watch(() => props.modelValue, (newVal) => {
		keyword.value = newVal;
		searchAction(keyword.value)
	});
	watch(() => props.searchCate, (newVal) => {
		searchCate.value = newVal;
	});

	// 历史记录存储 key
	const HISTORY_KEY = 'search_history'
	// 最大历史记录数量
	const MAX_HISTORY_COUNT = 10

	// 初始化历史记录
	const records = ref<String[]>([])
	// 从本地存储加载历史记录
	const loadHistory = () => {
		try {
			const savedHistory = uni.getStorageSync(HISTORY_KEY)
			if (savedHistory) {
				records.value = JSON.parse(savedHistory)
			}
		} catch (error) {
			console.error('加载历史记录失败:', error)
		}
	}
	// 添加搜索关键词到历史记录
	const addToHistory = (keyword : string) => {
		loadHistory()
		if (!keyword.trim()) return // 空关键词不添加
		// 移除已存在的相同关键词(避免重复)
		let newHistory = records.value.filter(item => item !== keyword)
		// 添加到开头(最新使用)
		newHistory.unshift(keyword)
		// 限制数量
		if (newHistory.length > MAX_HISTORY_COUNT) {
			newHistory = newHistory.slice(0, MAX_HISTORY_COUNT)
		}
		// 更新历史记录
		records.value = newHistory
		// 保存到本地存储
		saveHistory()
	}
	// 保存历史记录到本地存储
	const saveHistory = () => {
		try {
			uni.setStorageSync(HISTORY_KEY, JSON.stringify(records.value))
		} catch (error) {
			console.error('保存历史记录失败:', error)
		}
	}
	// 搜索指定关键字的商品
	function searchAction(value : string) {
		if(value== ""){
			uni.showToast({
				//搜索值不能为空
				title:t('searchKeyNotEmpty'),
				icon:"none",
				duration:2000
			})
		}else{
			// 更新父组件值
			emits('update:modelValue', value);
			emits('update:searchCate', searchCate.value);
			emits('search', value, searchCate.value);
			
			// 更新全局状态
			commonStore.setKeyWord(value);
			keyword.value = value
		}
		// params.value.product_name = value
		// params3.value.funpalytitle = value
		// // 添加到历史记录
		// addToHistory(value);
		// // 请求数据  searchCate.value == "0"  searchCate废弃
		// if (commonStore.tabsIndex == "0") {
		// 	console.log("搜索盲盒", params.value)
		// 	commonStore.setTabsIndex('0')
		// 	getMenuList(params.value);
		// }
		// else if (commonStore.tabsIndex == "1") {
		// 	// 搜索广场
		// 	console.log("搜索广场", params3.value)
		// 	commonStore.setTabsIndex('1')
		// 	getPostList(params3.value)
		// }
	}
	//清空输入框时 搜索全部商品
	// function searchAll() {
	// 	emits('update:modelValue', '');
	// 	emits('update:searchCate', searchCate.value);
	// 	params.value.product_name = ""
	// 	getMenuList(params.value);
	// }
	const haveProduct = ref<Number>(0)

	// function goResultPage() {
	// 	uni.navigateTo({
	// 		url: `/pages/search/searchResult?haveProduct=${String(haveProduct.value)}`,
	// 	})
	// }
	const productList = ref<SearchProduct[]>([])
	// 搜索产品
	async function getMenuList(customParams : { current : number; product_name : string }) {
		const defaultParams = {
			current: 1,
		};
		const finalParams = {
			...defaultParams,
			...customParams
		};
		// if (uni.getStorageSync('lang') == "") {
		// 	finalParams.lang = "cn"
		// }
		console.log("参数", finalParams)
		try {
			const response = await searchProduct(finalParams)
			if (response.code == 200 && response.msg == "success") {
				// 默认图片URL
				const DEFAULT_PRODUCT_IMAGE = '/static/images/dog.jpg';
				if (response.data != null) {
					productList.value = response.data.map((item : any) => ({
						...item,
						productImageSign: item.productImageSign || DEFAULT_PRODUCT_IMAGE, // 如果没有url，则添加默认值
					}));
					console.log("搜索结果", productList.value)
					// 将数据存入 store
					commonStore.setSearchProductList(productList.value);
					// haveProduct.value = 1
					// goResultPage()
				} else {
					productList.value = []
					commonStore.setSearchProductList([]);
				}
			} else {
				commonStore.setSearchProductList([]);
				// haveProduct.value = 0
				// goResultPage()
				// 显示提示框 商品不存在
				// isShow.value = true
				// title.value = response.msg
			}
		} catch (error) {
			let errorMsg = t('loadFail');
			// 尝试从错误对象中获取更具体的信息
			if (error.message) {
				errorMsg += error.message;
			} else if (typeof error === 'string') {
				errorMsg += error;
			}
			haveProduct.value = 0
			// goResultPage()
			isShow.value = true
			title.value = errorMsg
		}
	}
	const postList = ref<SearchPost[]>([])
	// 搜索帖子
	async function getPostList(customParams : { current : number; funpalytitle : string }) {
		const defaultParams = {
			current: 1,
		};
		const finalParams = {
			...defaultParams,
			...customParams
		};
		console.log("参数", finalParams)
		try {
			const response = await searchFunplay(finalParams)
			if (response.code == 200 && response.msg == "success") {
				// 默认图片URL
				const DEFAULT_PRODUCT_IMAGE = '/static/images/dog.jpg';
				if (response.data != null) {
					postList.value = response.data.map((item : any) => ({
						...item,
						uerr_sign: item.uerr_sign || DEFAULT_PRODUCT_IMAGE, // 如果没有url，则添加默认值
					}));
					console.log("搜索帖子结果", postList.value)
					// 将数据存入 store
					commonStore.setSearchPostList(postList.value);
					if (postList.value.length < 8) {
						commonStore.setNoMorePost(true)
					}
				} else {
					postList.value = []
					commonStore.setSearchPostList([]);
				}
			} else {
				commonStore.setSearchPostList([]);
				// 显示提示框 商品不存在
				// isShow.value = true
				// title.value = response.msg
			}
		} catch (error) {
			let errorMsg = t('loadFail');
			// 尝试从错误对象中获取更具体的信息
			if (error.message) {
				errorMsg += error.message;
			} else if (typeof error === 'string') {
				errorMsg += error;
			}
			isShow.value = true
			title.value = errorMsg
		}
	}

</script>

<style scoped lang="scss">
	.logo {
		margin: 0.23rem 0 0 0.43rem;
		width: 8.56rem;
		height: 2.63rem;
		z-index: 3;
	}

	.logo2 {
		margin: 0.6rem 0 0 0.8rem;
		width: 2.2rem;
		height: 2.2rem;
		line-height: 2.2rem;
		border-radius: 50%;
		z-index: 3;
	}

	.left-icon {
		width: 1.5rem;
		height: 1.5rem;
		margin-top: 0.35rem;
		// margin: -3rem 0 0 0.5rem;
		/* #ifdef  MP-WEIXIN*/
		// margin: 0rem 0 0 0.5rem;
		/* #endif*/
	}

	.search {
		position: relative;
		margin: 0.83rem 0 0 0.1rem;
		// width: 12.94rem;
		width: 80%;
		height: 1.94rem;
		z-index: 3;
		/* #ifdef  MP-WEIXIN*/
		width: 8.5rem;
		/* #endif*/
	}

	.icon-camera {
		position: absolute;
		top: 0.2rem;
		right: 0.7rem;
		width: 1.5rem;
		height: 1.5rem;
	}
</style>